package com.gaofans.nrpc.client.handler;

import com.gaofans.nrpc.common.context.ContextRequest;
import com.gaofans.nrpc.common.context.ContextResponse;
import com.gaofans.nrpc.common.context.SelectableExecutor;
import com.gaofans.nrpc.common.protocol.RpcResponse;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author GaoFans
 */
@ChannelHandler.Sharable
public class ContextBindHandler extends MessageToMessageCodec<RpcResponse, ContextRequest> {

    private final static Logger LOGGER = LoggerFactory.getLogger(ContextBindHandler.class);

    private final SelectableExecutor chooser;

    public ContextBindHandler(SelectableExecutor chooser) {
        this.chooser = chooser;
    }


    @Override
    protected void encode(ChannelHandlerContext ctx, ContextRequest contextRequest, List<Object> out) {
        LOGGER.debug("request:{} executor:{}",contextRequest.getSequenceId(),contextRequest.executor());
        out.add(contextRequest.getRequest());
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, RpcResponse response, List<Object> in) {
        ContextResponse contextResponse = new ContextResponse.ContextResponseBuilder(response).executor(chooser).build();
        LOGGER.debug("response:{} executor:{}",response.getSequenceId(),contextResponse.executor());
        in.add(contextResponse);
    }
}
